<template>
  <basic-dialog
    top="8vh"
    width="85%"
    title="关联品类"
    :visible="visible"
    :show-footer="false"
    :handleClose="handleClose"
  >
    <el-row>
      <el-col :span="12" class="left-col">
        <SearchForm ref="searchFormRef" @search="handleSearch" />
        <el-divider class="divider" content-position="left">条件查询结果：</el-divider>
        <ListSearch
          ref="searchListRef"
          v-loading="searchList.loading"
          :data-source="searchList.dataSource"
          :checked-list="searchList.checkedNodes"
          @checked="updateSearchCheckedNodes"
        />
        <el-divider content-position="left">品类树选择：</el-divider>
        <ListTree
          ref="treeListRef"
          check-strictly
          v-loading="treeList.loading"
          :data-source="treeList.dataSource"
          :checked-list="treeList.checkedNodes"
          @checked="updateTreeCheckedNodes"
        />
      </el-col>
      <el-col :span="12">
        <div class="selected-card">
          <ResultHeader
            ref="resultHeaderRef"
            :result-list="resultList.dataSource"
            :confirm-loading="btnLoading.confirm"
            @confirm="handleConfirm"
            @clear="clearResultList"
            @senior="updateResultListBySeniorSearch"
          />
          <el-divider />
          <ListResult
            v-loading="resultList.loading"
            :data-source="resultList.dataSource"
            @update="updateResultList"
          />
        </div>
      </el-col>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import SearchForm from './SearchForm';
import ListSearch from './ListSearch';
import ListTree from './ListTree';
import ListResult from './ListResult';
import ResultHeader from './ResultHeader';
import { isResponseSuccess } from '@/utils/bizUtils';
import {
  queryAllCategoryService,
  searchDialogCategoryService,
  cateLabelSeniorSearchService
} from '@/api/public';
export default {
  components: {
    BasicDialog,
    SearchForm,
    ListSearch,
    ListTree,
    ListResult,
    ResultHeader
  },
  props: {
    // 弹窗显示隐藏
    visible: {
      type: Boolean,
      default: false,
    },
    // 确认方法
    onConfirm: {
      type: Function,
      default: () => {},
    },
    // 回显已关联的品类集合
    onEcho: {
      type: Function,
      default: () => [],
    }
  },
  data () {
    return {
      searchList: { // 查询结果
        loading: false, // 加载状态
        dataSource: [], // 数据源
        checkedNodes: [], // 选中的节点
      },
      treeList: { // 树形结构
        loading: false, // 加载状态
        dataSource: [], // 数据源
        checkedNodes: [], // 选中的节点
      },
      resultList: { // 结果集合
        loading: false, // 加载状态
        dataSource: [], // 数据源
      },
      btnLoading: { // 按钮loading
        confirm: false, // 确定按钮
      },
    }
  },
  watch: {
    // 监听弹窗显示隐藏
    visible: {
      handler (val) {
        val ? this.initDialogData() : this.clearAllList()
      },
      immediate: true,
    },
  },
  methods: {
    // 关闭弹窗
    handleClose () {
      this.$emit('update:visible', false)
    },
    // 条件查询
    async handleSearch (formData) {
      const data = { ...formData }
      const loadingFn = state => { this.searchList.loading = state }
      const res = await searchDialogCategoryService(data, loadingFn)
      this.searchList.dataSource = res?.retData ?? []
    },
    // 确定
    async handleConfirm () {
      const loadingFn = state => { this.btnLoading.confirm = state }
      const res = await this.onConfirm(this.resultList.dataSource, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        this.handleClose()
      }
    },
    // 初始打开弹框的相关数据
    initDialogData () {
      this.setTreeList()
      this.setHistoryResultList()
    },
    // 设置品类树集合
    async setTreeList () {
      const data = {}
      const loadingFn = state => { this.treeList.loading = state }
      const res = await queryAllCategoryService(data, loadingFn)
      this.treeList.dataSource = res?.retData ?? []
    },
    // 设置历史已关联结果集合
    async setHistoryResultList () {
      const loadingFn = state => { this.resultList.loading = state }
      const res = await this.onEcho(loadingFn)
      this.updateTreeCheckedNodes(res?.retData ?? [])
      this.updateResultList()
    },
    // 更新条件查询选中的节点
    updateSearchCheckedNodes (list) {
      this.searchList.checkedNodes = list
      list.forEach(item => {
        const index = this.treeList.checkedNodes.findIndex(node => node.categoryUuid === item.categoryUuid)
        if (index > -1) this.treeList.checkedNodes.splice(index, 1)
      })
      this.updateResultList()
    },
    // 更新树形结构选中的节点
    updateTreeCheckedNodes (list) {
      this.treeList.checkedNodes = list
      list.forEach(item => {
        const index = this.searchList.checkedNodes.findIndex(node => node.categoryUuid === item.categoryUuid)
        if (index > -1) this.searchList.checkedNodes.splice(index, 1)
      })
      this.updateResultList()
    },
    // 更新结果集合
    updateResultList (uuids) {
      this.removeResultList(uuids)
      const allList = [...this.searchList.checkedNodes, ...this.treeList.checkedNodes]
      this.resultList.dataSource = _.uniqBy(allList, 'categoryUuid')
    },
    // 更新高级关联结果集合
    async updateResultListBySeniorSearch (categoryUuids) {
      const data = categoryUuids
      const loadingFn = state => { this.resultList.loading = state }
      const res = await cateLabelSeniorSearchService(data, loadingFn)
      const treeConcatList = [...this.treeList.checkedNodes, ...res?.retData ?? []]
      this.updateTreeCheckedNodes(_.uniqBy(treeConcatList, 'categoryUuid'))
      this.updateResultList()
    },
    // 移除已删除的品类集合
    removeResultList (uuids) {
      if (!uuids) return
      // 移除查询集合已删除的品类集合
      this.searchList.checkedNodes = this. searchList.checkedNodes.filter(item => uuids.includes(item.categoryUuid))
      // 移除品类树已删除的品类集合
      this.treeList.checkedNodes = this.treeList.checkedNodes.filter(item => uuids.includes(item.categoryUuid))
    },
    // 清空所有数据集合
    clearAllList () {
      this.searchList.dataSource = [] // 查询结果
      this.treeList.dataSource = [] // 树形结构
      this.resultList.dataSource = [] // 结果集合
      this.$refs.searchFormRef?.clearForm() // 清空查询表单
      this.$refs.resultHeaderRef?.clearSeniorLinked() // 清空高级关联内容
    },
    // 清空结果集合
    clearResultList () {
      const content = '确定后将清空所有已选品类，您确认吗？'
      this.$confirm(content, '清空', {
        type: 'warning',
      }).then(() => {
        this.searchList.checkedNodes = [] // 查询结果
        this.treeList.checkedNodes = [] // 树形结构
        this.updateResultList()
      }).catch(() => {})
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .el-divider--horizontal {
  margin: 10px 0;
}
.left-col {
  border-right: 1px dashed #dadada;
  padding-right: 20px;
}
.selected-card {
  padding: 10px;
  margin-left: 10px;
  max-height: 700px;
  overflow: auto;
}
</style>
